package com.yty.product.controller;

import com.yty.product.apidata.OrderDetailInput;
import com.yty.product.apidata.ProductInfoOutput;
import com.yty.product.entity.ProductCategory;
import com.yty.product.entity.ProductInfo;
import com.yty.product.service.ProductCategoryService;
import com.yty.product.service.ProductInfoService;
import com.yty.product.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RequestMapping("product")
@RestController
public class ProductController {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private ProductCategoryService productCategoryService;

    @PostMapping("decreaseStock")
    public void decreaseStock(@RequestBody List<OrderDetailInput> orderDetailInputs) {
        //TODO 非null
        productInfoService.decreaseStock(orderDetailInputs);
    }

    @PostMapping("listForOrder")
    public List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIds) {
        //TODO productIds非空
        return productInfoService.listInProductId(productIds);
    }

    @GetMapping("list")
    public List<ProductVO> list() {
        //1.查询所有上架商品
        List<ProductInfo> productInfos = productInfoService.listOnShelves();
        List<Integer> types = productInfos.parallelStream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
        List<ProductCategory> categorys = productCategoryService.listInType(types);

        return categorys.stream().map(category -> {
            ProductVO productVO = new ProductVO();
            productVO.setName(category.getCategoryName());
            productVO.setType(category.getCategoryType());
            productVO.setProducts(productInfos.stream()
                    .filter(product -> Objects.equals(product.getCategoryType(), category.getCategoryType()))
                    .map(ProductInfo::toProductInfoVo).collect(Collectors.toList()));
            return productVO;
        }).collect(Collectors.toList());
    }
}
